<?php

class GameInitAction extends SzAbstractAction
{
    protected $paramTypes = array(
        SzAbstractAction::TYPE_INT
    );

    /**
     * 获取玩家信 息
     *
     * @param int $userId
     * @return SzResponse
     */
    public function execute($userId)
    {
        /**
         * @var ModuleProfileVo $profile
         * @var ModuleProfileInfoVoList $profileInfoList
         * @var ModulePaymentVo $profilePayment
         * @var ModuleItemVoList $itemList
         * @var ItemLogsVoList $itemLogsList
         * @var WarehouseVoList $warehouseList
         * @var GroundVoList $groundList
         * @var PlantVoList $plantList
         * @var PlantSeedVoList $seedList
         * @var BuildingVoList $buildingList
         * @var OrderVoList $orderList
         * @var OrderBoardVoList $orderBoardList
         * @var OrderBoardVoList $orderBoardRewardList
         * @var FriendsVo $friends
         * @var FriendCodeVo $friendCode
         * @var GoodsVoList $goodsList
         * @var MissionVoList $missionList
         * @var DebrisVoList $debrisList
         * @var CollectionsVoList $collectionList
         * @var HandbookVoList $handbookList
         * @var MineVoList $mineList
         * @var array $globalDropInfo
         * @var int $behaviourCount
         * @var string $townName
         * @var IkebanaVoList $ikebanaList
         * @var CultivateLandVoList $cultivateLandList ,
         * @var CultivateFlowerVoList $cultivateFlowerList ,
         * @var ShareVoList $shareList ,
         * @var VideoVoList $videoList ,
         * @var NewCultivateLandVoList $newCultivateLandList ,
         * @var ModuleProfileInfoVo $profileInfo
         * @var ActivitySevenEventVoList $sevenEventList
         * @var ActivityDailyLoginVoList $dailyLoginList
         */
        list(
            $profile,
            $profileInfoList,
            $profilePayment,
            $itemList,
            $itemLogsList,
            $warehouseList,
            $groundList,
            $plantList,
            $seedList,
            $buildingList,
            $orderList,
            $orderBoardList,
            $orderBoardRewardList,
            $requestList,
            $selfRequestList,
            $friendList,
            $friendCode,
            $goodsList,
            $missionList,
            $debrisList,
            $collectionList,
            $handbookList,
            $mineList,
            $townName,
            $buildingItems,
            $ikebanaList,
            $shareList,
            $videoList,
            $newCultivateLandList,
            $cultivateTouchUsersNum,
            $compensateOrder,
            $compensateOne,
            $sevenEventList,
            $npcOrderNewList,
            $npcOrderOldList,
            $npcOrderRefreshTime,
            $activityList,
            $mailRedPoint,
            $friendCount,
            $dailyLoginList,
            $eventInviteStatus,
            ) = GameService::get()->init($userId);

        $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);

        $moreGame = $redisDb->get(GameConst::CACHE_KEY_MORE_GAME_STATUS);

        $hotPlay = $redisDb->get(GameConst::CACHE_KEY_HOT_PLAY_STATUS);

        $gmStatus = $redisDb->get(GameConst::CACHE_KEY_GM_STATUS);

        $shareStatus = $redisDb->get(GameConst::CACHE_KEY_SHARE_STATUS);

        if (!SzConfig::get()->loadAppConfig('app', 'GM_OPEN')) {
            $gmStatus = 0;
        }

        $noticeStatus = $redisDb->get(GameConst::CACHE_KEY_NOTICE_STATUS);

        $watchList = $redisDb->hGetAll(GameConst::CACHE_KEY_NEW_CULTIVATE_WATCH . $userId);

        $diff = 0;
        if (SzConfig::get()->loadAppConfig('app', 'GM_OPEN')) {
            $redisDb = SzDbFactory::get()->getDb(null, SzAbstractDb::DB_TYPE_REDIS);
            $diff = $redisDb->hGet(GameConst::CACHE_KEY_DIFF_TIME, $userId);
            if (!$diff) {
                $diff = 0;
            }
        }

        $reqTime = GameService::get()->getReqTime();
        $profileInfo = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_DAILY_FIRST_LOGIN, false);
        $dailyFirstLogin = 0;
        if (!$profileInfo) {
            $profileInfo = new ModuleProfileInfoVo(
                $userId,
                GameConst::USER_INFO_TYPE_DAILY_FIRST_LOGIN,
                1,
                $reqTime,
                true
            );
            $profileInfoList->addElement($profileInfo);
            $profileInfoList->setElement(GameConst::USER_INFO_TYPE_DAILY_FIRST_LOGIN, $profileInfo);
            SzPersister::get()->setVoList($profileInfoList);
            $dailyFirstLogin = 1;
        } else {
            // 日期不一致
            if(SzTime::getDate($profileInfo->getTime()) != SzTime::getDate($reqTime)) {
                $profileInfo->setTime($reqTime);
                $profileInfo->setInfo(1);
                $profileInfoList->updateElement(GameConst::USER_INFO_TYPE_DAILY_FIRST_LOGIN, $profileInfo);
                SzPersister::get()->setVoList($profileInfoList);
                $dailyFirstLogin = 1;
            }
        }

        $dailyGiftPackList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_DAILY_GIFT_PACK);
        $activityFirstPayList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_FIRST_PAY);
        if ($activityFirstPayList) {
            $activityFirstPayList = $activityFirstPayList->toArray();
        } else {
            $activityFirstPayList = array();
        }

        SeedService::get()->setFlowerLevel($userId,$reqTime,false,$redisDb);

        $guildId = GuildService::get()->getUserGuildId($userId,$profileInfoList);
        $guildChat = array();
        $platformData = $profileInfoList->getElement(GameConst::USER_INFO_TYPE_USER_PLATFORM,false);
        $platformId = '';
        if ($platformData){
            $platformId = $platformData->getRawInfo();
        }

        if ($guildId) {
            $redis = new Redis();
            $dbConfig = SzConfig::get()->loadAppConfig('database', 'Redis');
            $redisConfig = array(
                'server' => $dbConfig[0]['READER_HOST'][0][0],
                'port' => $dbConfig[0]['READER_HOST'][0][1],
                'password' => $dbConfig[0]['READER_PWD']
            );

            $redis->connect($redisConfig['server'],$redisConfig['port']);
            if ($redisConfig['password']) {
                $redis->auth($redisConfig['password']);
            }

            if ($platformId != ''){
                $guildChat = $redis->lRange($platformId.'-GuildChat:'.$guildId,0,-1);
            }
            else{
                $guildChat = $redis->lRange('GuildChat:'.$guildId,0,-1);
            }

        }

        if (GuildService::get()->getUserGuildId($userId,$profileInfoList)) {
            TrainingService::get()->updateProgress($userId,GameConst::TRAINING_TASK_JOIN_GUILD,1);
        }

        $guildCollection = $redisDb->get(GameConst::CACHE_GUILD_SHARE_COLLECTION_CACHE_KEY.$userId);
        $guildCollection = $guildCollection ? json_decode($guildCollection,true) : array();


        $activityValentineConf = array();
        $activityConf = array();
        $christmasConf = array();
        $activityConfs = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_EVENT, null, true);
        foreach ($activityConfs as $key=>$conf){
            if ($conf['type'] == 15){
                $activityValentineConf = $conf;
            }
            if ($conf['type'] == 17){
                $activityConf = $conf;
            }
            if ($conf['type'] == 30){
                $christmasConf = $conf;
            }
            //读取最新的配置
//            if (!empty($activityValentineConf) && !empty($activityConf)){
//                break;
//            }
        }

        //获取玩家当前正在开启的巧月活动或者儿童节活动
        $platformPre = GameConst::PLATFORM_TIME_ARRAY[$platformId];
        $commonActivityRange = array(
            'start' => 0,
            'end' => 0,
            'triggerLv' => 0
        );
        if ($activityConf){
            $sysConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_SYSTEM_UNLOCK, $activityConf['functionId'], true);
            /**
             * @var $actCommonDataList ActivityCommonDataVoList
             * @var $actCommonData ActivityCommonDataVo
             */
            $actCommonDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_COMMON);
            $actCommonData = $actCommonDataList->getElement($activityConf['indexId'],false);
            $actStart = strtotime($activityConf[$platformPre.'TriggerTime']);
            $actEnd = strtotime($activityConf[$platformPre.'EndTime']);
            $actCommonTime = $actEnd - $actStart;
            if ($actCommonData){
                $mineStart = $actCommonData->getCreateTime();
                $mineEnd = $actCommonData->getEndTime();
                //验证玩家自己的活动是否结束
                if($reqTime >= $mineStart && $reqTime <= $mineEnd){
                    $commonActivityRange['start'] = $mineStart;
                    $commonActivityRange['end'] = $mineEnd;
                }
                else{
                    if ($actStart <= $reqTime && $actEnd >= $reqTime && $mineEnd < $actStart){
                        $actCommonData->setUsePoint(0);
                        $actCommonData->setTotalPoint(0);
                        $actCommonData->setRewardInfo('');
                        $actCommonData->setCreateTime($reqTime);
                        $actCommonData->setEndTime($reqTime + $actCommonTime);
                        $actCommonDataList->updateElement($activityConf['indexId'],$actCommonData);
                        $commonActivityRange['start'] = $reqTime;
                        $commonActivityRange['end'] = $reqTime + $actCommonTime;

                        /**
                         * 获取目标玩家数据
                         * @var $taskDataList ActivityTaskVoList
                         */
                        //更新任务数据
                        $taskDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_TASK);
                        $taskDatas = $taskDataList->toArray();
                        if (!empty($taskDatas)){
                            foreach ($taskDatas as $position=>$data){
                                if ($position > 1){
                                    $taskDataList->deleteElement($position);
                                    SzPersister::get()->setVoList($taskDataList);
                                }
                            }
                        }
                    }
                }
            }
            else{
                if ($actStart <= $reqTime && $actEnd >= $reqTime){
                    $actCommonData = new ActivityCommonDataVo(
                        $userId, // userId
                        $activityConf['indexId'], //$activityId
                        0, // $usePoint
                        0, // $totalPoint
                        '',//$rewardInfo
                        $reqTime,//$createTime
                        (($reqTime + $actCommonTime) == $reqTime) ? $activityConf['endTime'] : ($reqTime + $actCommonTime),//$endTime
                        true
                    );

                    $actCommonDataList->addElement($actCommonData);
                    $actCommonDataList->setElement($activityConf['indexId'],$actCommonData);
                    $commonActivityRange['start'] = $reqTime;
                    $commonActivityRange['end'] = $reqTime + $actCommonTime;
                }
            }
            SzPersister::get()->setVoList($actCommonDataList);
            $commonActivityRange['triggerLv'] = $sysConfig['level'];
        }

        //获取玩家当前正在开启的女王节类型活动
        $valentineActivityRange = array(
            'start' => 0,
            'end' => 0,
            'triggerLv' => 0
        );
        if ($activityValentineConf){
            $valentineConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_SYSTEM_UNLOCK, $activityValentineConf['functionId'], true);
            /**
             * @var $valentineDataList ActivityValentineInfoVoList
             * @var $valentineData ActivityValentineInfoVo
             * @var $activityValentineOrderList ActivityValentineOrderVoList
             * @var $activityValentineOrder ActivityValentineOrderVo
             */
            $valentineDataList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_VALENTINE_INFO);
            $valentineData = $valentineDataList->getElement($activityValentineConf['indexId'],false);
            $activityValentineStart = strtotime($activityValentineConf[$platformPre.'TriggerTime']);
            $activityValentineEnd = strtotime($activityValentineConf[$platformPre.'EndTime']);
            $rangeTime = $activityValentineEnd - $activityValentineStart;
            if ($valentineData){
                $mineStart = $valentineData->getCreateTime();
                $mineEnd = $valentineData->getEndTime();
                //验证玩家自己的活动是否结束
                if($reqTime >= $mineStart && $reqTime <= $mineEnd){
                    $valentineActivityRange['start'] = $mineStart;
                    $valentineActivityRange['end'] = $mineEnd;
                }
            }
            else{
                if ($activityValentineStart <= $reqTime && $activityValentineEnd >= $reqTime){
                    $valentineData = new ActivityValentineInfoVo($userId,$activityValentineConf['indexId'],0,[],$reqTime,0, $reqTime,$reqTime + $rangeTime,true);
                    $valentineDataList->addElement($valentineData);
                    $valentineDataList->setElement($activityValentineConf['indexId'],$valentineData);
                    SzPersister::get()->setVoList($valentineDataList);
                    $valentineActivityRange['start'] = $reqTime;
                    $valentineActivityRange['end'] = $reqTime + $rangeTime;
                }
            }
            $valentineActivityRange['triggerLv'] = $valentineConfig['level'];
        }

        //获取玩家当前正在开启的翻牌子类活动
        $christmasActivityRange = array(
            'start' => 0,
            'end' => 0,
            'triggerLv' => 0
        );
        if ($christmasConf){
            $christmasConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_GAME_SYSTEM_UNLOCK, $christmasConf['functionId'], true);
            /**
             * @var $christmasCommonList ChristmasCommonVoList
             * @var $christmasFloorData ChristmasCommonVo
             * @var $activityValentineOrderList ActivityValentineOrderVoList
             * @var $activityValentineOrder ActivityValentineOrderVo
             */
            $christmasCommonList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_CHRISTMAS_COMMON);
            $christmasFloorData = $christmasCommonList->getElement($christmasConf['indexId'],false);
            $christmasStart = strtotime($christmasConf[$platformPre.'TriggerTime']);
            $christmasEnd = strtotime($christmasConf[$platformPre.'EndTime']);
            $rangeTime = $christmasEnd - $christmasStart;
            if ($christmasFloorData){
                $mineStart = $christmasFloorData->getCreateTime();
                $mineEnd = $christmasFloorData->getEndTime();
                //验证玩家自己的活动是否结束
                if($reqTime >= $mineStart && $reqTime <= $mineEnd){
                    $christmasActivityRange['start'] = $mineStart;
                    $christmasActivityRange['end'] = $mineEnd;
                }
            }
            else{
                if ($christmasStart <= $reqTime && $christmasEnd >= $reqTime){
                    $physical = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'treasureEnergyFrist', true)['value'];
                    $christmasFloorData = new ChristmasCommonVo(
                        $userId,
                        $christmasConf['indexId'],
                        $physical,
                        0,
                        1,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        json_encode('0,0,0,0,0,0,0'),
                        json_encode(''),
                        json_encode(''),
                        0,
                        json_encode('0,0,0'),
                        $reqTime,
                        $reqTime,
                        $reqTime,
                        $reqTime + $rangeTime,
                        true
                    );
                    $christmasCommonList->addElement($christmasFloorData);
                    $christmasCommonList->setElement($christmasConf['indexId'],$christmasFloorData);
                    SzPersister::get()->setVoList($christmasCommonList);
                    $christmasActivityRange['start'] = $reqTime;
                    $christmasActivityRange['end'] = $reqTime + $rangeTime;

                    //创建送礼数据
                    /**
                     * @var $christmasSendList ChristmasSendGiftVoList
                     * @var $christmasSendData ChristmasSendGiftVo
                     */
                    $christmasSendList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_ACTIVITY_CHRISTMAS_SEND_GIFT);
                    $christmasSendData = $christmasSendList->getElement($christmasConf['indexId'],false);
                    if (!$christmasSendData){
                        $christmasSendData = new ChristmasSendGiftVo(
                            $userId,
                            $christmasConf['indexId'],
                            0,
                            0,
                            '',
                            $reqTime,
                            $reqTime,
                            $reqTime + $rangeTime,
                            true
                        );
                        $christmasSendList->addElement($christmasSendData);
                        $christmasSendList->setElement($christmasConf['indexId'],$christmasSendData);
                        SzPersister::get()->setVoList($christmasSendList);
                    }
                }
            }
            $christmasActivityRange['triggerLv'] = $christmasConfig['level'];
        }

        return $this->buildResponse(array(
            'profile' => $profile->toArray(),
            'profileInfoList' => $profileInfoList->toArray(true),
            'profilePayment' => $profilePayment->toArray(),
            'itemList' => $itemList->toArray(),
            'itemLogsList' => $itemLogsList->toArray(),
            'warehouseList' => $warehouseList->toArray(),
            'groundList' => $groundList->toArray(),
            'plantList' => $plantList->toArray(),
            'seedList' => $seedList->toArray(),
            'buildingList' => $buildingList->toArray(),
            'orderList' => $orderList->toArray(),
            'orderBoardList' => $orderBoardList->toArray(),
            'orderBoardReward' => $orderBoardRewardList->toArray(),
            'requestList' => $requestList,
            'friends' => $selfRequestList,
            'selfRequestList' => $friendList,
            'friendCode' => $friendCode->toArray(),
            'goodsList' => $goodsList->toArray(),
            'missionList' => $missionList->toArray(),
            'debrisList' => $debrisList->toArray(),
            'collectionInfoList' => $collectionList->toArray(),
            'handbookInfoList' => $handbookList->toArray(),
            'mineList' => $mineList->toArray(),
            'buildingItems' => $buildingItems,
            'townName' => $townName,
            'timezoneOffset' => SzUtility::getTimeZoneOffset(SzConfig::get()->loadAppConfig('app', 'TIMEZONE')),
            'ikebanaList' => $ikebanaList->toArray(),
            'ShareList' => $shareList->toArray(),
            'VideoList' => $videoList->toArray(),
            'SevenEventList' => $sevenEventList->toArray(),
            'moreGame' => $moreGame, // 更多活动开关
            'hotPlay' => $hotPlay, // 全民热玩开关
            'newCultivateLandList' => $newCultivateLandList->toArray(),
            'watchList' => $watchList,
            'diff' => $diff,
            'gmStatus' => $gmStatus,
            'dailyFirstLogin' => $dailyFirstLogin,
            'cultivateTouchUsersNum' => $cultivateTouchUsersNum,
            'compensateOrder' => $compensateOrder,
            'compensateOne' => $compensateOne,
            'noticeStatus' => $noticeStatus,
            'npcOrderNewList' => $npcOrderNewList,
            'npcOrderOldList' => $npcOrderOldList,
            'npcOrderRefreshTime' => $npcOrderRefreshTime,
            'activityList' => $activityList,
            'mailRedPoint' => $mailRedPoint,
            'friendCount' => $friendCount,
            'shareStatus' => $shareStatus,
            'dailyLoginList' => $dailyLoginList->toArray(),
            'eventInviteStatus' => $eventInviteStatus,
            'dailyGiftPackList' => $dailyGiftPackList->toArray(),
            'activityFirstPayList' => $activityFirstPayList,
            'treeInfo' => TreeService::get()->info($userId),
            'guildChat' => $guildChat,
            'guildCollection' => $guildCollection,
            'activityRange' => $commonActivityRange,
            'activityValentineRange' => $valentineActivityRange,
            'videoInfoList' => VideoInfoService::get()->info($userId),
            'userShopList' => UserShopService::get()->shopInfo($userId,$reqTime),
            'christmasActivityRange' => $christmasActivityRange,
            'flowerOrderComNum' => ChallengeOrderService::get()->getFlowerOrderNum($userId,$reqTime)
        ));
    }
}
